package cn.edu.jdbc;

import cn.edu.jdbc.util.DruidUtil;
import cn.edu.jdbc.util.DruidUtils;
import cn.edu.jdbc.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 注册
 * 防止SQL注入攻击：
 * PreparedStatement
 */
public class JdbcDemo14 {
    public static void main(String[] args) {
        Connection conn = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            conn = DruidUtils.getConn();
            //TODO...
            String sql = "insert into mydb01(username,password,nickname,age) values(?,?,?,?)";
            ps = conn.prepareStatement(sql);
            //接收用户输入的内容
            Scanner sc = new Scanner(System.in);
            System.out.println("开始注册了~~~");
            System.out.println("请输入用户名：");
            String username = sc.nextLine();
            System.out.println("请输入密码：");
            String password = sc.nextLine();
            System.out.println("请输入昵称：");
            String nickname = sc.nextLine();
            System.out.println("请输入年龄：");
            int age = sc.nextInt();

            /*设置参数 ?对应的值
                ?是整数的话，ps.setInt(...);
                ?是字符串的话，ps.setString(...);
             */
            ps.setString(1, username);
            ps.setString(2, password);
            ps.setString(3, nickname);
            ps.setInt(4,age);
            //执行
            int rows = ps.executeUpdate();
            if (rows > 0){
                System.out.println("注册成功~~~");
            } else {
                System.out.println("注册失败~~");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(rs, ps, conn);
        }
    }
}
